package zzj;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;

import javax.swing.JFileChooser;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class WhereIsMovie {
	private SqliteDao sqldDao = new SqliteDao();

	public void scanMovieInfo(String path,String volSerial,String volName){
		sqldDao.delMovieInfo(path, volSerial); // 清空历史数据
		getMovieFromPath(path, volSerial,volName);
	}
	
	/**
	 * 根据路径扫描硬盘上的电影文件
	 * @param path
	 * @param volSerial
	 * @param volName
	 */
	public void getMovieFromPath(String path,String volSerial,String volName) {

		String movieTittle = "";
		String movieFolder = ""; 
		String movieFileName = "";
		String movieFilePath = "";
//		String volSerial = getVolSerial(path);
		Map<String, String> map = new HashMap<String, String>();
		File fpath = new File(path);
		File[] fs = fpath.listFiles();
		for (int i = 0; i < fs.length; i++) {
			if(fs[i].isHidden()){
				continue;
			}
			if (fs[i].isDirectory()) {
				if ("BDMV".equals(fs[i].getName())) {
					movieTittle = fs[i].getParentFile().getName();
					movieFolder = fs[i].getParentFile().getPath();
					movieFileName = movieTittle;
					movieFilePath = movieFolder;
					map.put("MOVIE_TITTLE", movieTittle);
					map.put("MOVIE_FOLDER", movieFolder);
					map.put("MOVIE_FILE_NAME", movieFileName);
					map.put("MOVIE_FILE_PATH", movieFilePath);
					map.put("VOL_SERIAL", volSerial);
					map.put("VOL_NAME", volName);
					sqldDao.insertMovieInfo(map);
					break;

				} else {
					getMovieFromPath(fs[i].toString(),volSerial,volName);
				}
			} else {
				if (isMoiveFile(fs[i])) {
					movieTittle = fs[i].getParentFile().getName();
					movieFolder = fs[i].getParentFile().getPath();
					movieFileName = fs[i].getName();
					movieFilePath = fs[i].getPath();
					map.put("MOVIE_TITTLE", movieTittle);
					map.put("MOVIE_FOLDER", movieFolder);
					map.put("MOVIE_FILE_NAME", movieFileName);
					map.put("MOVIE_FILE_PATH", movieFilePath);
					map.put("VOL_SERIAL", volSerial);
					map.put("VOL_NAME", volName);
					sqldDao.insertMovieInfo(map);
				}
			}
		}
	}

	/**
	 *  获得电影信息表数据
	 * @param name
	 * @return
	 */
	public TableModel searchMovieInfo(String name) {
		LinkedHashMap<String, String> colNameMap = new LinkedHashMap<String, String>();
		Vector<String> columnNames = new Vector<String>();
		Vector<Vector> alldata = new Vector<Vector>();
		colNameMap.put("MOVIE_TITTLE", "电影名称");
		colNameMap.put("VOL_NAME", "卷标");
		colNameMap.put("MOVIE_FILE_NAME", "文件名");
		colNameMap.put("MOVIE_FOLDER", "所在文件夹");
		colNameMap.put("MOVIE_FILE_PATH", "路径");
		colNameMap.put("VOL_SERIAL", "卷序列号");
		for (String str : colNameMap.keySet()) {
			columnNames.add(colNameMap.get(str));
		}
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		list = sqldDao.searchMovieInfo(name);
//		System.out.println(list);
		// String
		for (HashMap<String, String> map : list) {
			Vector<String> data = new Vector<String>();
			for (String key : colNameMap.keySet()) {
				data.add(map.get(key));
			}
			alldata.add(data);
		}
		TableModel dataModel = new DefaultTableModel(alldata, columnNames){
			 /**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int rowIndex, int columnIndex) {
			        return false;
			    }
		};
		return dataModel;
	}

	/**
	 * 判断是否是电影文件
	 * @param file
	 * @return
	 */
	public Boolean isMoiveFile(File file) {
		String fileType=getProperties("fileType");
		
//		String type[] = { ".mkv", ".mp4", ".mov",".avi",".rm","rmvb",".iso" };
		String type[] = fileType.split(";");
		for (int i = 0; i < type.length; i++) {
			if (file.getName().toLowerCase().endsWith(type[i])) {
				return true;
			}
		}
		return false;
	}

	/**
	 *  新增路径
	 * @param path
	 */
	public void addPath(File path) {
		sqldDao.insertConf(path.toString());
	}

	/**
	 * 根据路径获得卷序列号
	 * @param path
	 * @return
	 */
	public String getVolSerial(String path) {
		String volSerial = "";
		String line = "";
		try {
			Process proc = Runtime.getRuntime().exec(
					"cmd.exe /c vol " + path.substring(0, 2));
			// System.out.println("cmd /c vol "+path.substring(0, 2));
			BufferedReader br = new BufferedReader(new InputStreamReader(
					proc.getInputStream(), "GBK"));
			while ((line = br.readLine()) != null) {
//				 System.out.println(line);
//				line = new String(line.getBytes(), "UTF8");
//				 System.out.println("UTF8  "+"卷的序列号是");
				if (line.indexOf("卷的序列号是") != -1) {
					volSerial = line.replace("卷的序列号是", "").toString().trim();
					break;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.err.println(e.getClass().getName() + ": " + e.getMessage());
			e.printStackTrace();
		}
		// System.out.println(volSerial);
		return volSerial;
	}
	/**
	 * 根据路径获得卷标
	 * @param path
	 * @return
	 */
	public String getVolName(String path) {
		String volName = "";
		String line = "";
		try {
			Process proc = Runtime.getRuntime().exec(
					"cmd.exe /c vol " + path.substring(0, 2));
			// System.out.println("cmd /c vol "+path.substring(0, 2));
			BufferedReader br = new BufferedReader(new InputStreamReader(
					proc.getInputStream(), "GBK"));
			while ((line = br.readLine()) != null) {
				// System.out.println(line);
//				line = new String(line.getBytes(), "UTF8");
				if (line.indexOf("中的卷是") != -1) {
					volName = line.substring(line.indexOf("中的卷是")+"中的卷是".length()).trim();
					break;
				}
			}
		} catch (IOException e) {
			System.err.println(e.getClass().getName() + ": " + e.getMessage());
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// System.out.println(volSerial);
		return volName;
	}

	/**
	 * 返回配置表数据
	 * @return
	 */
	public TableModel getConfData() {
		LinkedHashMap<String, String> colNameMap = new LinkedHashMap<String, String>();
		Vector<String> columnNames = new Vector<String>();
		Vector<Vector> alldata = new Vector<Vector>();
		colNameMap.put("VOL_NAME", "卷标");
		colNameMap.put("PATH", "扫描路径");
		colNameMap.put("IS_VAILD", "是否连接");
		colNameMap.put("VOL_SERIAL", "卷的序列号");
		for (String str : colNameMap.keySet()) {
			columnNames.add(colNameMap.get(str));
		}
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		list = sqldDao.getConfData();
//		System.out.println(list);
		// String
		for (HashMap<String, String> map : list) {
			Vector<String> data = new Vector<String>();
			for (String key : colNameMap.keySet()) {
				if ("IS_VAILD".equals(key)) {
					data.add(isPathVaild(map.get("PATH"),map.get("VOL_SERIAL")));
				} else {
					data.add(map.get(key));
				}
			}
			alldata.add(data);
		}
		TableModel dataModel = new DefaultTableModel(alldata, columnNames){
			 /**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int rowIndex, int columnIndex) {
			        return false;
			    }
		};;
		return dataModel;
	}

	/**
	 * 判断设置的路径当前是否连接
	 * @param path
	 * @param curVolSerial
	 * @return
	 */
	public String isPathVaild(String path, String curVolSerial) {
		String result = "未连接";
		String c="";
		if ( getVolSerial(path).equals(curVolSerial)) {
			result = "已连接";
		}
		return result;
	}

	/**
	 * 删除路径
	 * @param path
	 * @param volSerial
	 */
	public void delPath(String path, String volSerial) {
		// TODO Auto-generated method stub
		sqldDao.delMovieInfo(path, volSerial);
		sqldDao.delConf(path, volSerial);
	}
	/**
	 * 获取properties配置文件参数
	 * @param paramName
	 * @return
	 */
	public String getProperties(String paramName){
		String result="";
		InputStream ins=this.getClass().getClassLoader().getResourceAsStream("./config.properties");
		Properties p=new Properties();
		try {
			p.load(ins);
			ins.close();
			result=p.getProperty(paramName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 设置配置文件参数
	 * @param paramName
	 * @param value
	 */
	public void setProperties(String paramName,String value){
		Properties p=new Properties();
		InputStream ins=this.getClass().getClassLoader().getResourceAsStream("./config.properties");
		try {
			p.load(ins);
			OutputStream out=new FileOutputStream("./config.properties");
			p.setProperty(paramName, value);
			p.store(out, "Update "+paramName+" to "+value);
		} catch (Exception e) {
			// TODO: handle exception
			System.err.println("updating "+paramName+" value error");
		}
	}
}
